package vip.zhenzicheng.nettybasic.checkread;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.AllArgsConstructor;
import vip.zhenzicheng.nettybasic.NettyConst;

import java.net.InetSocketAddress;

/**
 * @author zhenzicheng
 * @date 2022-06-12 19:47
 */
@AllArgsConstructor
public class EchoClientCR {

  private final int port;
  private final String host;

  public static void main(String[] args) throws InterruptedException {
    new EchoClientCR(NettyConst.ECHO_PORT, NettyConst.LOCALHOST).start();
  }

  public void start() throws InterruptedException {
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(group)
          .channel(NioSocketChannel.class)
          .remoteAddress(new InetSocketAddress(host, port))
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel channel) throws Exception {
              channel.pipeline().addLast(new EchoClientCRHandler());
            }
          });

      ChannelFuture future = bootstrap.connect().sync();
      future.channel().closeFuture().sync();
    } finally {
      group.shutdownGracefully().sync();
    }
  }
}
